<template>
  <!-- 创建账号表单 -->
  <div class="formDiv">
    <el-form ref="form" :rules="rules" :model="form" label-width="110px" autocomplete="new-password">

      <el-form-item label="用户名：" prop="userName" autocomplete="new-password">
        <!-- @input="form.userName = form.userName.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, '')" -->
        <el-input v-model.trim="form.userName" placeholder="请输入用户名" maxLength="20" autocomplete="new-password"></el-input>
      </el-form-item>

      <el-form-item label="用户密码：" prop="password" autocomplete="new-password">
        <el-input type="password" v-model.trim="form.password" :type="pwInputtype" placeholder="请输入用户密码" maxLength="20" autocomplete="new-password">
          <i slot="suffix" class="el-input__icon el-icon-view" @click="pwInputtype = (pwInputtype == 'password' ? 'text' : 'password')"></i>
        </el-input>
      </el-form-item>

      <el-form-item label="重复密码：" prop="repeatPassword">
        <el-input type="password" v-model.trim="form.repeatPassword" :type="repwInputtype" placeholder="请再次输入密码" maxLength="20">
          <i slot="suffix" class="el-input__icon el-icon-view" @click="repwInputtype = (repwInputtype == 'password' ? 'text' : 'password')"></i>
        </el-input>
      </el-form-item>

      <el-form-item label="手机号码：" prop="userPhone">
        <el-input v-model.trim="form.userPhone" placeholder="请输入手机号码" :maxlength="11" @input="form.userPhone = form.userPhone.replace(/[^\d]/g,'')"></el-input>
      </el-form-item>
      
      <el-form-item label="手机验证码：" prop="authCode">
        <div class="codeDiv">
          <el-input v-model.trim="form.authCode" placeholder="请输入手机验证码" maxLength="6"></el-input>
          <div class="sendCodeBtn" @click="sendAuthCode" v-if="textCount < 0">发送验证码</div>
          <div class="cantSendBtn" v-if="textCount >= 0">{{'已发送(' + (textCount < 10 ? ('0' + textCount) : textCount) + '秒)'}}</div>
        </div>
      </el-form-item>

      <el-form-item>
        <div class="btnDiv">
          <Buttons @prev="prev" @createUser="createUser" :buttons="buttons"></Buttons>
        </div>
      </el-form-item>
      <!-- <el-form-item>
        <div class="btnDiv">
          <div class="btn" @click="prev">上一步</div>
          <div class="btn" style="background-color: #045db9; color: #f1f2f4" @click="createUser">创建用户</div>
        </div>
      </el-form-item> -->
    </el-form>

  </div>
</template>

<script>
	import config from '@/utils/config.js'
	import {isPhone, isEmptyStr} from "@/utils/util"
	import {request} from '@/utils/request.js'
  import { artificialRegister, register } from "@/common/api/logOrReg.js";
  import { getAuthCode } from "@/common/api.js";
  export default {
    props: {
      value: {
        type: Number,
        default: 1
      }
    },
    data() {
      var checkUser = (rule,value,callback)=>{
				let check = /^[\u4E00-\u9FA5]+$/
				let check1 = /^[\u4E00-\u9FA5a-zA-Z0-9_]{4,16}$/
				// console.log(value);
				// console.log(!check1.test(value) && check.test(value) && value.length==2,'!check1.test(value) && check.test(value) && value.length==2');
				
				if(isEmptyStr(value)) {
					callback(new Error('请输入用户名')) 
				}else if(check.test(value) && value.length>8){
					callback(new Error('全汉字只能是2-8位'))
				}else if(!check1.test(value)){
					if(check.test(value) && value.length<2){
						callback(new Error('4-16个字节，仅可包含大小写字母，数字，中文，下划线'))
					}else{
						callback()
					}
				}else{
					callback()
				}
			}
			var checkPsw = (rule,value,callback)=>{
				// console.log(value);
				let check2 = /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$).{6,18}$/
				let passwordCheck = !check2.test(this.form.password)
				var reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
				if(isEmptyStr(value)) {
					callback(new Error('请输入用户密码')) 
				}else if(passwordCheck || reg.test(value)){
					callback(new Error('6-18位，必须至少同时包含数字和大小写字母'))
				}else{
					callback()
				}
			}
			var checkRepasw = (rule,value,callback)=>{
				// console.log(value)
				if(isEmptyStr(value)) {
					callback(new Error('请输入重复密码')) 
				}else if(this.form.password != value) {
					callback(new Error('重复密码不一致')) 
				}else{
					callback()
				}
			}
			var checkPhone = (rule,value,callback)=>{
				if(isEmptyStr(value)) {
					callback(new Error('请输入手机号码')) 
				}else if(!isPhone(value)){
					callback(new Error('请输入正确的手机号码'))
				}else{
					callback()
				}
			}

      return {
        buttons:[
          {text:"上一步",type:"normal",size:"l",method:"prev"},
          {text:"创建用户",type:"success",size:"l",method:"createUser"},
        ],
        form: {
          authType: 'register'
        },
        pwInputtype: 'password',
				repwInputtype: 'password',
				rules: {
					userName: [
            {required:true, trigger:'blur', validator:checkUser}
          ],
					password: [
            {required:true, trigger:'blur', validator:checkPsw}
          ],
					repeatPassword: [
            {required:true, trigger:'blur', validator:checkRepasw}
          ],
					userPhone: [
            {required:true, trigger:'blur', validator:checkPhone}
          ],
					authCode: [
            {required:true, trigger:'blur', message:'请输入验证码'}
          ]
				},
				textCount: -1 //短信倒计时
      }
    },
    methods: {
			/**
			 * 注册用户
			 */
			async createUser() {
        let ok = false
				this.$refs['form'].validate(valid => {
          if(valid) ok = true;
        })
        if(!ok) return ;
        let ns = this
        let clueSource = localStorage.getItem('clueSource')// 线索数据区分0人工认证、1非人工认证
        let form = {
          "clueType": this.$route.query.type ? this.$route.query.type : 1,
          "clueSource": clueSource,
          "attractInvestmentClueExpand": {
            ...JSON.parse(localStorage.getItem('preForm'))
          },
          "companyUser": {
            ...ns.form
          }
        }
        if(clueSource == 0) {
          let res = await artificialRegister(form)
          if(res.code == 200) {
            ns.next()
            localStorage.removeItem('preForm')
          } else {
            ns.$message.error(res.msg)
          }
        } else {
          let res = await register(form)
          if(res.code == 200) {
            ns.next()
            localStorage.removeItem('preForm')
          } else {
            ns.$message.error(res.msg)
          }
        }
			},
			/**
			 * 发送短信验证码
			 */
			async sendAuthCode() {
				let ns = this
				if(!isPhone(ns.form.userPhone)) {
					ns.$message.error('手机号码格式不正确')
					return
				}
				let data = {
					userPhone: ns.form.userPhone,
					authType: 'register'
				}
        let res = await getAuthCode(data)
        if(res.code == 200) {
          ns.textCount = 120
          var timer = setInterval(counting, 1000);
          function counting() {
            ns.textCount--
            if (ns.textCount < 0) {
              clearInterval(timer)
            }
          }
        } else {
          ns.$message.error(res.msg)
        }
			},
      prev() {
        this.$emit('input', this.value-1)
      },
      next() {
        this.$emit('input', this.value+1)
      }
    }
  }
</script>

<style lang="scss" scoped>
.formDiv {
  margin: 0 auto 100px auto;
  width: 600px;
  text-align: left;
  .agreementDiv:hover {
    cursor: pointer;
    text-decoration: underline;
  }
  .btnDiv {
    display: flex;
    .btn {
      background-color: #f1f2f4;
      color: #045db9;
      margin-right: 20px;
      width: 100px;
      text-align: center;
      font-size: 15px;
      border-radius: 5px;
      &:hover {
        cursor: pointer;
        box-shadow: 0px 0px 5px #888888;
        transition: all 0.2s ease 0s;
      }
    }
  }
  .codeDiv {
    display: flex;
    .el-input {
      margin-right: 10px;
    } 
    .sendCodeBtn {
      white-space: nowrap;
      background-color: #f1f2f4;
      color: #045db9;
      width: 120px;
      text-align: center;
      border-radius: 4px;
      &:hover {
        cursor: pointer;
        box-shadow: 0px 0px 3px #888888;
        transition: all 0.2s ease 0s;
      }
    }
    .cantSendBtn {
      white-space: nowrap;
      background-color: #f1f2f4;
      color: #045db9;
      width: 120px;
      text-align: center;
      border-radius: 4px;
      &:hover {
        cursor: pointer;
      }
    }
  }
}
</style>